package os.filesystem.tool;

import os.filesystem.exception.FSMalformedCommandException;
import os.filesystem.file.Directory;
import os.filesystem.file.exception.FSMissingFileException;

public final class Rm extends FSTool {

	public static final String COMMAND_NAME = "rm";
	
	public void rm(String filename) {
		Directory wd = FSState.workingDir();
		try {
			String abs = wd.remove(filename);
			if (abs != null) {
				FSState.io.delete(abs);
				FSState.io.write(FSState.workingDir());
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}
	
	public void rm(Command command) throws FSMalformedCommandException, FSMissingFileException{
		Directory wd = FSState.workingDir();
		
		if(command.getNonOptionArguments().size() > 1 && command.getCommandNameArgument().getArgument().equals(COMMAND_NAME)){
			for(Argument arg : command.getNonOptionArguments()){
				if(wd.contains(arg.getArgument())){
					//TODO must be executed in transaction
					try {
						String abs = wd.remove(arg.getArgument());
						if (abs != null) {
							FSState.io.delete(abs);
							FSState.io.write(FSState.workingDir());
						}
					} catch (Exception e) {
						throw new FSMissingFileException("No file: " + arg.getArgument());
					} 
				}else{
					throw new FSMissingFileException("No file: " + arg.getArgument());
				}
			}
		}else{
			throw new FSMalformedCommandException("Wrong command. Please check manual for syntax.");
		}
	}
	
	@Override
	public void execute(Command command) throws FSMissingFileException, FSMalformedCommandException{
		rm(command);
	}
}
